import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate';
//如果您不想手动管理localStorage，可以取消注释并使用vuex-persistedstate插
// 件，它会自动将指定的Vuex状态（如token和userInfo）同步到localStorage：
import router from '../router';
// 注册 Vuex
Vue.use(Vuex)

// 创建 store 实例
const store = new Vuex.Store({
    state: {
        // 状态数据
        config: {},
        token: '',
        userInfo: null,
    },
    mutations: {
        // 变更状态的方法

        setToken(state, token) {
            state.token = token;
        },
        setUserInfo(state, userInfo) {
            state.userInfo = userInfo;

        },
        clearUserInfo(state) {
            state.userInfo = null;
        },
        setConfig(state, config) {
            state.config = config;
      },
    },
    getters: {
        getToken: state => state.token,
        getUserInfo: state => state.userInfo,
        getConfig: state => state.config,
        isLoggedIn: state => !!state.token && !!state.userInfo,
    },
    plugins: [
        createPersistedState({
            paths: ['token', 'userInfo'], // 持久化 token 和 userInfo
        }),
    ],
    actions: {
        Login({ commit }, { token, userInfo }) {
            commit('setToken', token);
            commit('setUserInfo', userInfo);
        },
        Logout({ commit }) {
            commit('setToken', '');
            commit('clearUserInfo');
            // 跳转到登录页面
            router.push('/login').catch(err => {
                // 处理导航重复的错误
                if (err.name !== 'NavigationDuplicated') {
                    console.error('导航错误:', err);
                }
            });
        },
        clearToken({ commit }) {
            commit('setToken', '');
            commit('clearUserInfo');
        },
      }
})

export default store